"""
SimpleAPI ORM 模型基类

提供简化的模型定义接口，完全封装 Tortoise ORM 的模型实现。
用户只需要继承 Model 类，无需了解底层的 Tortoise 模型。
"""

from typing import Any, Dict, List, Optional, Type, Union, ClassVar
import inspect
from tortoise.models import Model as TortoiseModel
from tortoise.models import ModelMeta as TortoiseModelMeta
from .fields import BaseField


class ModelMeta(TortoiseModelMeta):
    """模型元类，处理字段转换"""
    
    def __new__(cls, name: str, bases: tuple, namespace: dict, **kwargs):
        # 转换我们的字段为 Tortoise 字段
        for field_name, field_value in list(namespace.items()):
            if isinstance(field_value, BaseField):
                # 将我们的字段转换为 Tortoise 字段
                namespace[field_name] = field_value.get_tortoise_field()
        
        return super().__new__(cls, name, bases, namespace, **kwargs)


class Model(TortoiseModel, metaclass=ModelMeta):
    """
    SimpleAPI ORM 模型基类
    
    提供简化的模型接口，封装所有 Tortoise ORM 的复杂性。
    用户只需要继承这个类并定义字段即可。
    """
    
    class Meta:
        abstract = True
    
    # 类方法 - 简化的查询接口
    @classmethod
    async def create_record(cls, **kwargs) -> 'Model':
        """
        创建新记录
        
        Args:
            **kwargs: 字段值
            
        Returns:
            创建的模型实例
        """
        return await cls.create(**kwargs)
    
    @classmethod
    async def get_record(cls, **kwargs) -> Optional['Model']:
        """
        获取单个记录
        
        Args:
            **kwargs: 查询条件
            
        Returns:
            模型实例或 None
        """
        try:
            return await cls.get(**kwargs)
        except cls.DoesNotExist:
            return None
    
    @classmethod
    async def get_or_create_record(cls, defaults: Dict = None, **kwargs) -> tuple['Model', bool]:
        """
        获取或创建记录
        
        Args:
            defaults: 创建时的默认值
            **kwargs: 查询条件
            
        Returns:
            (模型实例, 是否为新创建)
        """
        return await cls.get_or_create(defaults=defaults or {}, **kwargs)
    
    @classmethod
    async def update_records(cls, filter_kwargs: Dict, **update_kwargs) -> int:
        """
        更新记录
        
        Args:
            filter_kwargs: 过滤条件
            **update_kwargs: 更新的字段值
            
        Returns:
            更新的记录数量
        """
        return await cls.filter(**filter_kwargs).update(**update_kwargs)
    
    @classmethod
    async def delete_records(cls, **kwargs) -> int:
        """
        删除记录
        
        Args:
            **kwargs: 删除条件
            
        Returns:
            删除的记录数量
        """
        return await cls.filter(**kwargs).delete()
    
    @classmethod
    async def list_records(cls, 
                          limit: int = None,
                          offset: int = None, 
                          order_by: List[str] = None,
                          **kwargs) -> List['Model']:
        """
        获取记录列表
        
        Args:
            limit: 限制数量
            offset: 偏移量
            order_by: 排序字段
            **kwargs: 过滤条件
            
        Returns:
            模型实例列表
        """
        queryset = cls.filter(**kwargs)
        
        if order_by:
            queryset = queryset.order_by(*order_by)
        if offset:
            queryset = queryset.offset(offset)
        if limit:
            queryset = queryset.limit(limit)
            
        return await queryset
    
    @classmethod
    async def count_records(cls, **kwargs) -> int:
        """
        统计记录数量
        
        Args:
            **kwargs: 过滤条件
            
        Returns:
            记录数量
        """
        return await cls.filter(**kwargs).count()
    
    @classmethod
    async def exists_record(cls, **kwargs) -> bool:
        """
        检查记录是否存在
        
        Args:
            **kwargs: 查询条件
            
        Returns:
            是否存在
        """
        return await cls.filter(**kwargs).exists()
    
    @classmethod
    async def bulk_create_records(cls, objects: List[Dict], batch_size: int = 1000) -> List['Model']:
        """
        批量创建记录
        
        Args:
            objects: 对象数据列表
            batch_size: 批次大小
            
        Returns:
            创建的模型实例列表
        """
        instances = [cls(**obj) for obj in objects]
        created_instances = await cls.bulk_create(instances, batch_size=batch_size)
        return created_instances if created_instances is not None else instances
    
    @classmethod
    async def bulk_update_records(cls, instances: List['Model'], 
                                 fields: List[str], batch_size: int = 1000) -> None:
        """
        批量更新记录
        
        Args:
            instances: 模型实例列表
            fields: 要更新的字段列表
            batch_size: 批次大小
        """
        if instances:
            await cls.bulk_update(instances, fields, batch_size=batch_size)
    
    @classmethod
    async def truncate_table(cls) -> None:
        """清空表数据"""
        await cls.all().delete()
    
    @classmethod
    def query_builder(cls) -> 'QueryBuilder':
        """
        创建查询构建器
        
        Returns:
            查询构建器实例
        """
        from .query import QueryBuilder
        return QueryBuilder(cls)
    
    # 实例方法
    async def save_record(self, **kwargs) -> None:
        """
        保存记录
        
        Args:
            **kwargs: 保存选项
        """
        await self.save(**kwargs)
    
    async def delete_record(self) -> None:
        """删除当前记录"""
        await self.delete()
    
    async def refresh_record(self) -> None:
        """刷新记录数据"""
        await self.refresh_from_db()
    
    def to_dict(self, exclude: List[str] = None, include: List[str] = None) -> Dict:
        """
        转换为字典
        
        Args:
            exclude: 排除的字段
            include: 包含的字段
            
        Returns:
            字典数据
        """
        data = {}
        fields = self._meta.fields_map.keys()
        
        if include:
            fields = [f for f in fields if f in include]
        if exclude:
            fields = [f for f in fields if f not in exclude]
            
        for field in fields:
            value = getattr(self, field, None)
            if hasattr(value, 'isoformat'):  # 处理日期时间
                value = value.isoformat()
            data[field] = value
            
        return data
    
    @classmethod
    def from_dict(cls, data: Dict) -> 'Model':
        """
        从字典创建模型实例（不保存到数据库）
        
        Args:
            data: 字典数据
            
        Returns:
            模型实例
        """
        return cls(**data)
    
    def __repr__(self) -> str:
        """字符串表示"""
        pk_value = getattr(self, self._meta.pk.model_field_name, None)
        return f"<{self.__class__.__name__}: {pk_value}>"
    
    def __str__(self) -> str:
        """字符串表示"""
        return self.__repr__()


class BaseModel(Model):
    """
    带有常用字段的基础模型
    
    包含 id、created_at、updated_at 等常用字段
    """
    
    class Meta:
        abstract = True


# 在模块级别导入字段函数
from .fields import primary_key, created_at, updated_at

# 动态添加字段到 BaseModel
BaseModel.id = primary_key()
BaseModel.created_at = created_at()
BaseModel.updated_at = updated_at() 